package com.atguigu.ssyx.acl.service.impl;

import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.model.acl.Permission;
import com.atguigu.ssyx.model.acl.RolePermission;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.acl.service.RolePermissionService;
import com.atguigu.ssyx.acl.utils.PermissionHelper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ZhangYK
 * @version 8.0
 * @title PermissionServiceImpl
 * @description
 * @create 2024/7/6 13:43
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Resource
    private RolePermissionService rolePermissionService;

    @Resource
    private PermissionService permissionService;

    /**
     * 获取菜单列表
     * @return
     */
    @Override
    public List<Permission> queryAllMenu() {
        //把权限数据结构构建成树形数据结构
        List<Permission> result = PermissionHelper.bulid(list());
        return result;
    }

    /**
     * 递归删除菜单
     * @param id
     */
    @Override
    public void removeChildById(Long id) {
        List<Long> list = new ArrayList<>();
        list.add(id);
        this.selectChildListById(id,list);
        baseMapper.deleteBatchIds(list);
    }

    /**
     * 获得所有菜单和已分配的菜单
     * @param roleId
     * @return
     */
    @Override
    public Map<String, Object> getPermissionByRoleId(Long roleId) {
        //所有菜单
        List<Permission> allPermissionList = PermissionHelper.bulid(list());
        List<Permission> buildAllPermissionList = PermissionHelper.bulid(allPermissionList);

        //根据roleId查询菜单
        List<RolePermission> rolePermissionList = rolePermissionService.lambdaQuery()
                .eq(RolePermission::getRoleId, roleId)
                .list();
        //获得已分配菜单id
        List<Long> permissionIdList = rolePermissionList.stream().map(rolePermission -> {
            return rolePermission.getPermissionId();
        }).collect(Collectors.toList());
        //封装已分配的菜单对象
        List<Permission> assignPermission = new ArrayList<>();
        for (Permission permission : buildAllPermissionList) {
            if (permission.getPid()==0){
                //父节点，顶层
                if (permissionIdList.contains(permission.getId())){
                    permission.setSelect(true);
                }
                this.setPermissionChildren(permission.getChildren(),permissionIdList);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("allPermissionList", allPermissionList);
        result.put("assignPermission", assignPermission);
        return result;
    }

    private void setPermissionChildren(List<Permission> children, List<Long> permissionIdList) {
        for (Permission permission : children) {
            if (permissionIdList.contains(permission.getId())){
                permission.setSelect(true);
            }
            this.setPermissionChildren(permission.getChildren(),permissionIdList);
        }
    }

    /**
     * 递归获取子id
     * @param id
     * @param idList
     */
    private void selectChildListById(Long id, List<Long> idList) {
        lambdaQuery()
                .eq(Permission::getPid,id)
                .list()
                .stream()
                .forEach(permission -> {
                    idList.add(permission.getId());
                    selectChildListById(permission.getId(), idList);
                });
    }

    /**
     * 分配菜单
     * @param roleId
     * @param permissionIds
     */
    @Override
    public void saveRolePermissionRealtionShip(Long roleId, Long[] permissionIds){
        //删除用户分配的角色数据
        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));

        //分配新的角色
        List<RolePermission> rolePermissionList = new ArrayList<>();
        for(Long permissionId : permissionIds) {
            if(StringUtils.isEmpty(roleId)) continue;
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionList.add(rolePermission);
        }
        rolePermissionService.saveBatch(rolePermissionList);
    }

    /**
     * 根据用户获取菜单数据
     * @param roleId
     * @return
     */
    @Override
    public Map<String, Object> findPermissionByRoleId(Long roleId) {
        //查询所有的角色
        List<Permission> allPermissionList =queryAllMenu();
        List<Permission> assignPermission1 =baseMapper.selectList(null);

        //拥有的角色id
        List<RolePermission> existRolePermissionList = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id", roleId).select("permission_id"));
        List<Long> existPermissionList = existRolePermissionList.stream().map(c->c.getPermissionId()).collect(Collectors.toList());

        //对角色进行分类
        List<Permission> assignPermission2 = new ArrayList<Permission>();
        for (Permission permission : assignPermission1) {
            //已分配
            if(existPermissionList.contains(permission.getId())) {
                assignPermission2.add(permission);
            }
        }
        List<Long> assignPermission = assignPermission2.stream().map(c->c.getId()).collect(Collectors.toList());

        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assignPermission", assignPermission);
        roleMap.put("allPermissionList", allPermissionList);
        return roleMap;
    }
}
